<template>
  <div class="users-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="搜索用户名/邮箱/手机号"
              clearable
              @change="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleSearch"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 统计信息 -->
      <div class="stats-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">总用户数:</span>
              <span class="stat-value">{{ userStats.total }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">今日新增:</span>
              <span class="stat-value">{{ userStats.todayNew }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">活跃用户:</span>
              <span class="stat-value">{{ userStats.active }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">禁用用户:</span>
              <span class="stat-value">{{ userStats.disabled }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 用户表格 -->
      <el-table :data="userList" v-loading="loading" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="scope">
            <el-avatar :src="scope.row.avatar" :alt="scope.row.username">
              {{ scope.row.username.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="orderCount" label="订单数" width="100" />
        <el-table-column prop="totalAmount" label="消费金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewUser(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 用户详情弹窗 -->
    <el-dialog v-model="userDetailVisible" title="用户详情" width="800px">
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ currentUser.createTime }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
          <el-descriptions-item label="订单数量">{{ currentUser.orderCount }}</el-descriptions-item>
          <el-descriptions-item label="总消费">¥{{ currentUser.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 'active' ? 'success' : 'danger'">
              {{ currentUser.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const userDetailVisible = ref(false)
const currentUser = ref(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: null
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 用户统计
const userStats = ref({
  total: 12580,
  todayNew: 28,
  active: 12245,
  disabled: 335
})

// 用户列表
const userList = ref([
  {
    id: 1,
    username: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    avatar: '',
    orderCount: 25,
    totalAmount: '1,580.50',
    status: 'active',
    createTime: '2023-01-15 10:30:00',
    lastLoginTime: '2023-12-15 14:20:30'
  },
  {
    id: 2,
    username: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    avatar: '',
    orderCount: 12,
    totalAmount: '780.90',
    status: 'active',
    createTime: '2023-02-20 15:45:00',
    lastLoginTime: '2023-12-14 09:15:20'
  },
  {
    id: 3,
    username: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    avatar: '',
    orderCount: 5,
    totalAmount: '240.00',
    status: 'disabled',
    createTime: '2023-03-10 11:20:00',
    lastLoginTime: '2023-12-10 16:30:45'
  }
])

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.dateRange = null
  pagination.page = 1
  loadUserList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadUserList()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadUserList()
}

// 查看用户详情
const handleViewUser = (user) => {
  currentUser.value = user
  userDetailVisible.value = true
}

// 切换用户状态
const handleToggleStatus = async (user) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确认要${action}用户 "${user.username}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API
    user.status = user.status === 'active' ? 'disabled' : 'active'
    ElMessage.success(`${action}成功`)
    
    // 更新统计数据
    loadUserStats()
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确认要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 这里应该调用API
    const index = userList.value.findIndex(item => item.id === user.id)
    if (index > -1) {
      userList.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
    loadUserStats()
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    // 这里应该调用API
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.total = userStats.value.total
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 加载用户统计
const loadUserStats = async () => {
  try {
    // 这里应该调用API
    await new Promise(resolve => setTimeout(resolve, 200))
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  }
}

onMounted(() => {
  loadUserList()
  loadUserStats()
})
</script>

<style scoped>
.users-page {
  padding: 0;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stats-area {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.pagination-area {
  margin-top: 20px;
  text-align: center;
}

.user-detail {
  padding: 20px 0;
}
</style> 